<template>
  <h4>{{ title }}</h4>
  <canvas :id="key" class="c2d" width="1000" height="500"></canvas>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

const key = ref("c2d" + Math.floor(Math.random() * 10000));
const props = defineProps({
  title: String,
});

onMounted(() => {
  const canvas = document.querySelector(`#${key.value}`);

  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });

  // 1. 创建一个场景
  const scene = new THREE.Scene();

  {
    // 方向光1
    const color = 0xffffff;
    const intensity = 1;
    const light = new THREE.DirectionalLight(color, intensity);
    light.position.set(40, 40, 50);
    scene.add(light);
  }

  {
    // 方向光2
    const light = new THREE.DirectionalLight(0xffffff, 1);
    light.position.set(-10, -5, -30);
    scene.add(light);
  }

  // 创建物体
  const boxWidth = 10;
  const boxHeight = 10;
  const boxDepth = 10;
  const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth);
  var material = new THREE.MeshPhongMaterial({ color: 0x6688aa });
  var object = new THREE.Mesh(geometry, material);
  // 将物体添加到场景中
  scene.add(object);

  // 透视投影相机
  const fov = 40; // 视野范围
  const aspect = 2; // 相机默认值 画布的宽高比
  const near = 0.1; // 近平面
  const far = 1000; // 远平面
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  // 设置相机 x、y、z 位置
  camera.position.set(0, 50, 0);
  // 相机指向的场景中心
  camera.lookAt(0, 0, 0);

  // 底部网格（可以不设置）
  const gridHelper = new THREE.GridHelper(300, 25, 0x004444, 0x004444);
  scene.add(gridHelper);

  // 控制相机
  const controls = new OrbitControls(camera, canvas);
  controls.update();

  // 帧循环中更新相机位置
  function animateCamera() {
    requestAnimationFrame(animateCamera);
    // 让物体的朝向始终正对相机（主要设置）
    object.lookAt(camera.position);
    renderer.render(scene, camera);
  }

  animateCamera();
});
</script>

<style scoped>
.read-the-docs {
  color: #888;
}
</style>
